/**
 * Created by superman on 17/2/16.
 * http配置
 */

import axios from 'axios'
import store from './store'
import router from './router'
import qs from 'qs'

// axios 配置
axios.defaults.timeout = 5000;
//axios.defaults.baseURL = 'http://192.168.10.170:5000';
axios.defaults.baseURL = 'http://127.0.0.1:5000/';

axios.defaults.withCredentials = true;
//axios.options.xhr = { withCredentials : true };

// http request 拦截器
axios.interceptors.request.use(
    config => {
        //let curr_token = store.getters.curr_token;

        config.headers["Access-Control-Allow-Origin"] = "*";
        config.headers["Access-Control-Allow-Headers"] = "Authorization,Origin, X-Requested-With, Content-Type, Accept";
        config.headers["Access-Control-Allow-Methods"] = "GET,POST";

        config.headers['X-Requested-With'] = 'XMLHttpRequest';
        config.headers['Accept'] = 'application/json';

        let curr_token = localStorage.getItem('token');
        console.log("curr_token", curr_token);
        if (curr_token) {
            config.headers.Authorization = 'token ' + curr_token;
            console.log("Authorization:", config.headers.Authorization);
            console.log("headers:", config.headers);
        }
        return config;
    },
    err => {
        console.log("request err:", err);
        return Promise.reject(err);
    });

// http response 拦截器
axios.interceptors.response.use(
    response => {
        console.log("response:", JSON.stringify(response));//console : Error: Request failed with status code 402
        return response;
    },
    error => {
        if (error.response) {
          console.log("error.response.status", error.response.status);
          switch (error.response.status) {
            case 401:
              // 401 清除token信息并跳转到登录页面
              localStorage.removeItem('username')
              localStorage.removeItem('token')

              store.dispatch("resetUser");
              store.dispatch("resetToken");

              router.replace({
                        path: 'login',
                        query: {redirect: router.currentRoute.fullPath}
              })
            }
        }
        console.log(JSON.stringify(error));//console : Error: Request failed with status code 402
        return Promise.reject(error.response)
    });

export default axios;
